<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Member;

/**
 * MemberSearch represents the model behind the search form about `app\models\Member`.
 */
class MemberSearch extends Member
{
    public $start;
    public $end;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'usertype', 'status', 'create_time'], 'integer'],
            [['username', 'qq', 'mobile', 'zhuangtai', 'note','channel'], 'safe'],
            [['start', 'end'], 'string'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Member::find();

        $roles = Yii::$app->authManager->getRolesByUser(Yii::$app->user->id);
        $role = array_shift($roles);
        if($role->name=='查看会员渠道组') {
            $query->andWhere(['channel'=>Yii::$app->user->identity->username]);
        }

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'class'=>'backend\components\ReversePage',
                'pageSize' => 15,
            ],
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_ASC,
                ]
            ],
        ]);


        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        if(!empty($this->start)) {
            $query->andWhere(['>=', 'create_time', strtotime($this->start)]);
        }
        if(!empty($this->end)) {
            $query->andWhere(['<', 'create_time', strtotime($this->end)+3600*24]);

        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'usertype' => $this->usertype,
            'status' => $this->status,
            'create_time' => $this->create_time,
        ]);

        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'qq', $this->qq])
            ->andFilterWhere(['like', 'mobile', $this->mobile])
            ->andFilterWhere(['like', 'channel', $this->channel])
            ->andFilterWhere(['like', 'zhuangtai', $this->zhuangtai])
            ->andFilterWhere(['like', 'note', $this->note]);

        return $dataProvider;
    }
}
